package com.fortune.controller;

import com.fortune.base.BaseAPIExcution;
import com.fortune.common.paging.PagingData;
import com.fortune.constants.Constants;
import com.fortune.dto.excution.DstoreInExcution;
import com.fortune.dto.in.BackReturnOrder.ReturnOrderAddDto;
import com.fortune.dto.in.BackReturnOrder.ReturnOrderDetailAddDto;
import com.fortune.dto.in.BackReturnOrder.ReturnOrderEditDto;
import com.fortune.entity.DUserInfo;
import com.fortune.enums.DstoreInEnum;
import com.fortune.service.BackReturnOrderService;
import com.fortune.util.UUIDUtil;
import com.fortune.vo.BackReturnOrder.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/5/26 0026.
 */
@Api(value = "backReturnOrder", description = "经销商退押金工单", tags = {"经销商退押金工单"})
@RestController
@RequestMapping("backReturnOrder")
public class BackReturnOrderController {
    @Autowired
    private BackReturnOrderService backReturnOrderService;

    @ApiOperation(value = "经销商退押金工单列表", nickname = "returnOrderList", notes = "", tags={ "@郭阳" })
    @ApiImplicitParams({
            @ApiImplicitParam(name="page", value="第几页",paramType="query",dataType="int"),
            @ApiImplicitParam(name="length", value="每页容量",paramType="query",dataType="int"),
            @ApiImplicitParam(name="search", value="搜索",paramType="query",dataType="String"),
            @ApiImplicitParam(name="isAllow", value="批准状态（0全部1已批准2未批准）",paramType="query",dataType="int",allowableValues = "0,1,2"),
            @ApiImplicitParam(name="boxDriver", value="司机id",paramType="query",dataType="String"),
            @ApiImplicitParam(name="isAccount", value="交账状态（0全部1已交账2未交账）",paramType="query",dataType="int",allowableValues = "0,1,2"),
            @ApiImplicitParam(name="boxIsIn", value="入库状态（0全部1已入库2未入库）",paramType="query",dataType="int",allowableValues = "0,1,2"),
            @ApiImplicitParam(name="order", value="排序依据",paramType="query",dataType="string"),
            @ApiImplicitParam(name="type", value="排序类型(0升序,1降序,默认为1)",paramType="query",dataType="Integer",allowableValues = "0,1")
    })
    @GetMapping(value = "list",
            produces = { MediaType.APPLICATION_JSON_VALUE })
    public BaseAPIExcution<PagingData<List<ReturnOrder>>> list(HttpServletRequest request, @Validated @ApiIgnore ReturnOrderListDto returnOrderListDto) {
        HttpSession session = request.getSession();
        DUserInfo dUserInfo = (DUserInfo) session.getAttribute(Constants.SESSION_D_USER);
        String did = dUserInfo.getdId();
        returnOrderListDto.setPage((returnOrderListDto.getPage()-1)*10);
        List<ReturnOrder> findReturnOrderList = backReturnOrderService.findReturnOrderList(did, returnOrderListDto);
        Integer count = backReturnOrderService.returnOrderListCount(did, returnOrderListDto);
        for(ReturnOrder returnOrder : findReturnOrderList){
            /*开单人*/
            if(returnOrder.getCreateType().toString().equals("JXS")){
                returnOrder.setCreateUser(backReturnOrderService.findJXSName(returnOrder.getCreateUser(), did));
            }
            if(returnOrder.getCreateType().toString().equals("KH")){
                returnOrder.setCreateUser(backReturnOrderService.findKHName(returnOrder.getCreateUser()));
            }
            /*批准人*/
            if(returnOrder.getAllowUser() == null){
                returnOrder.setAllowUser("无");
            }else{
                returnOrder.setAllowUser(backReturnOrderService.findKDRName(returnOrder.getAllowUser(),did));
            }
            /*回收空箱司机*/
            if(returnOrder.getBoxDriver() == null){
                returnOrder.setBoxDriver("无");
            }else{
                returnOrder.setBoxDriver(backReturnOrderService.findSJName(returnOrder.getBoxDriver(), did));
            }
            /*库房验收人*/
            if(returnOrder.getStoreUser() == null){
                returnOrder.setStoreUser("无");
            }else{
                returnOrder.setStoreUser(backReturnOrderService.findKFName(returnOrder.getStoreUser(), did));
            }
        }
        for(ReturnOrder returnOrder1 : findReturnOrderList){
            if(returnOrder1.getCreateTime() != null){
                returnOrder1.setCreateTime(returnOrder1.getCreateTime().substring(0,10));
            }
            if (returnOrder1.getAllowTime() != null){
                returnOrder1.setAllowTime(returnOrder1.getAllowTime().substring(0,10));
            }
            if(returnOrder1.getAccountTime() != null){
                returnOrder1.setAccountTime(returnOrder1.getAccountTime().substring(0,10));
            }
            if(returnOrder1.getInTime() != null){
                returnOrder1.setInTime(returnOrder1.getInTime().substring(0,10));
            }
            if(returnOrder1.getReturnTime() != null){
                returnOrder1.setReturnTime(returnOrder1.getReturnTime().substring(0,10));
            }
        }
        PagingData pagingData = new PagingData<List<ReturnOrder>>();
        pagingData.setData(findReturnOrderList);
        pagingData.setRecordsTotal(count);
        return new DstoreInExcution<PagingData<List<ReturnOrder>>>(pagingData, DstoreInEnum.FIND_SUCCESS);
    }

    @ApiOperation(value = "添加退押金工单", nickname = "returnOrderAdd", notes = "", tags={ "@郭阳" })
    @PostMapping(value = "add",
            produces = { MediaType.APPLICATION_JSON_VALUE },
            consumes = { MediaType.APPLICATION_JSON_VALUE })
    public BaseAPIExcution<Void> add(HttpServletRequest request,@Validated @RequestBody ReturnOrderAddDto returnOrderAddDto) {
       HttpSession session = request.getSession();
        DUserInfo dUserInfo = (DUserInfo) session.getAttribute(Constants.SESSION_D_USER);
        String did = dUserInfo.getdId();
        String id = UUIDUtil.get32UUID();
        int addReturnOrder = backReturnOrderService.addReturnOrder(did, id, returnOrderAddDto);
        if(addReturnOrder < 1){
            return new DstoreInExcution<Void>(null, DstoreInEnum.FAILURE);
        }
        return new DstoreInExcution<Void>(null, DstoreInEnum.SUCCESS);
    }

    @ApiOperation(value = "添加退押金工单详情", nickname = "returnOrderDetailAdd", notes = "", tags={ "@郭阳" })
    @PostMapping(value = "detailAdd",
            produces = { MediaType.APPLICATION_JSON_VALUE },
            consumes = { MediaType.APPLICATION_JSON_VALUE })
    public BaseAPIExcution<Void> detailAdd(HttpServletRequest request,@Validated @RequestBody ReturnOrderDetailAddDto returnOrderDetailAddDto) {
        HttpSession session = request.getSession();
        DUserInfo dUserInfo = (DUserInfo) session.getAttribute(Constants.SESSION_D_USER);
        String did = dUserInfo.getdId();
        int addRedturnOrderDetails = backReturnOrderService.addRedturnOrderDetails(did, returnOrderDetailAddDto);
        if(addRedturnOrderDetails < 1){
            return new DstoreInExcution<Void>(null, DstoreInEnum.FAILURE);
        }
        return new DstoreInExcution<Void>(null, DstoreInEnum.SUCCESS);
    }

    @ApiOperation(value = "编辑退押金工单", nickname = "returnOrderEdit", notes = "", tags={ "@郭阳" })
    @PutMapping(value = "edit",
            produces = { MediaType.APPLICATION_JSON_VALUE },
            consumes = { MediaType.APPLICATION_JSON_VALUE })
    public BaseAPIExcution<Void> edit(HttpServletRequest request,@Validated @RequestBody ReturnOrderEditDto returnOrderEditDto) {
        HttpSession session = request.getSession();
        DUserInfo dUserInfo = (DUserInfo) session.getAttribute(Constants.SESSION_D_USER);
        String did = dUserInfo.getdId();
        int editReturnOrder = backReturnOrderService.editReturnOrder(did, returnOrderEditDto);
        if(editReturnOrder < 1){
            return new DstoreInExcution<Void>(null, DstoreInEnum.FAILURE);
        }
        return new DstoreInExcution<Void>(null, DstoreInEnum.SUCCESS);
    }

    @ApiOperation(value = "删除退押金工单", nickname = "returnOrderDelete", notes = "", tags={ "@郭阳" })
    @ApiImplicitParams({
            @ApiImplicitParam(name="orderId", value="退押金工单id",paramType="query",dataType="string",required=true),
            @ApiImplicitParam(name="clientId", value="客户id",paramType="query",dataType="string",required=true),
    })
    @DeleteMapping(value = "delete",
            produces = { MediaType.APPLICATION_JSON_VALUE })
    public BaseAPIExcution<Void> delete(HttpServletRequest request,@Validated @NotBlank(message="退押金工单id不能为空")String orderId,
                                        @Validated @NotBlank(message="客户id不能为空")String clientId) {
        HttpSession session = request.getSession();
        DUserInfo dUserInfo = (DUserInfo) session.getAttribute(Constants.SESSION_D_USER);
        String did = dUserInfo.getdId();
        int deleteRrturnOrder = backReturnOrderService.deleteRrturnOrder(did,orderId,clientId);
        if (deleteRrturnOrder < 1){
            return new DstoreInExcution<Void>(null, DstoreInEnum.FAILURE);
        }
        return new DstoreInExcution<Void>(null, DstoreInEnum.SUCCESS);
    }

    @ApiOperation(value = "退押金工单详情", nickname = "returnOrderInfo", notes = "", tags={ "@郭阳" })
    @ApiImplicitParams({
            @ApiImplicitParam(name="orderId", value="退押金工单id",paramType="query",dataType="string",required=true),
            @ApiImplicitParam(name="clientId", value="客户id",paramType="query",dataType="string",required=true),
    })
    @GetMapping(value = "info",
            produces = { MediaType.APPLICATION_JSON_VALUE })
    public BaseAPIExcution<List<ReturnOrderDetail>> info(HttpServletRequest request, @Validated @NotBlank(message="退押金工单id不能为空")String orderId,
                                              @Validated @NotBlank(message="客户id不能为空")String clientId) {
        HttpSession session = request.getSession();
        DUserInfo dUserInfo = (DUserInfo) session.getAttribute(Constants.SESSION_D_USER);
        String did = dUserInfo.getdId();
        List<ReturnOrderDetail> findReturnOrderDetailList = backReturnOrderService.findReturnOrderDetailList(did,clientId,orderId);
        for(ReturnOrderDetail returnOrderDetail : findReturnOrderDetailList){
            String targetType = returnOrderDetail.getTargetType();
            if(targetType.equals("M")){
                String findAbbreviation = backReturnOrderService.findAbbreviation(returnOrderDetail.getMid());
                returnOrderDetail.setAbbreviation(findAbbreviation);
            }
            if(targetType.equals("D")){
                returnOrderDetail.setAbbreviation("自营");
            }
        }
        return new DstoreInExcution<List<ReturnOrderDetail>>(findReturnOrderDetailList, DstoreInEnum.SUCCESS);
    }

    @ApiOperation(value = "批准退押金", nickname = "approvedReturnOrder", notes = "", tags={ "@郭阳" })
    @PutMapping(value = "approved",
            produces = { MediaType.APPLICATION_JSON_VALUE },
            consumes = { MediaType.APPLICATION_JSON_VALUE })
    public BaseAPIExcution<Void> approved(HttpServletRequest request,String orderId,String driverId) {
        HttpSession session = request.getSession();
        DUserInfo dUserInfo = (DUserInfo) session.getAttribute(Constants.SESSION_D_USER);
        String did = dUserInfo.getdId();
        String id = dUserInfo.getId();
        int approvedReturnOrder = backReturnOrderService.approvedReturnOrder(did, orderId,id,driverId);
        if(approvedReturnOrder < 1){
            return new DstoreInExcution<Void>(null, DstoreInEnum.FAILURE);
        }
        return new DstoreInExcution<Void>(null, DstoreInEnum.SUCCESS);
    }


    @ApiOperation(value = "客户列表", nickname = "clientList", notes = "", tags={ "@郭阳" })
    @GetMapping(value = "clientList",
            produces = { MediaType.APPLICATION_JSON_VALUE })
    public BaseAPIExcution<List<ClientList>> clientList(HttpServletRequest request) {
        HttpSession session = request.getSession();
        DUserInfo dUserInfo = (DUserInfo) session.getAttribute(Constants.SESSION_D_USER);
        String did = dUserInfo.getdId();
        List<ClientList> findClientList = backReturnOrderService.findClientList(did);
        return new DstoreInExcution<List<ClientList>>(findClientList, DstoreInEnum.SUCCESS);
    }

    @ApiOperation(value = "获取客户手机号", nickname = "clientPhone", notes = "", tags={ "@郭阳" })
    @ApiImplicitParam(name="clientId", value="客户id",paramType="query",dataType="string",required=true)
    @GetMapping(value = "clientPhone",
            produces = { MediaType.APPLICATION_JSON_VALUE })
    public BaseAPIExcution<String> clientPhone(@Validated @NotBlank(message="客户id不能为空")String clientId) {
        String findClientPhone = backReturnOrderService.findClientPhone(clientId);
        return new DstoreInExcution<String>(findClientPhone, DstoreInEnum.SUCCESS);
    }

    @ApiOperation(value = "商品列表", nickname = "productList", notes = "", tags={ "@郭阳" })
    @GetMapping(value = "productList",
            produces = { MediaType.APPLICATION_JSON_VALUE })
    public BaseAPIExcution<List<Product>> productList(HttpServletRequest request) {
        HttpSession session = request.getSession();
        DUserInfo dUserInfo = (DUserInfo) session.getAttribute(Constants.SESSION_D_USER);
        String did = dUserInfo.getdId();
        List<Product> products = new ArrayList<>();
        /*List<Product> findProductListByD = backReturnOrderService.findProductListByD(did);
        for(Product product1 : findProductListByD){
            product1.setAbbreviation("自营");
            products.add(product1);
        }*/
        List<MID> findMid = backReturnOrderService.findMid(did);
        for(MID mids : findMid){
            String mid = mids.getId();
            List<Product> findProductListByM = backReturnOrderService.findProductListByM(mid);
            for(Product product : findProductListByM){
                products.add(product);
            }
        }

        return new DstoreInExcution<List<Product>>(products, DstoreInEnum.SUCCESS);
    }

    @ApiOperation(value = "客户购买过的商品列表", nickname = "clientProductList", notes = "", tags={ "@郭阳" })
    @ApiImplicitParam(name="clientId", value="客户id",paramType="query",dataType="string",required=true)
    @GetMapping(value = "clientProductList",
            produces = { MediaType.APPLICATION_JSON_VALUE })
    public BaseAPIExcution<List<Product>> clientProductList(HttpServletRequest request,@Validated @NotBlank(message="客户id不能为空")String clientId) {
        HttpSession session = request.getSession();
        DUserInfo dUserInfo = (DUserInfo) session.getAttribute(Constants.SESSION_D_USER);
        String did = dUserInfo.getdId();
        List<ProductId> findProductIdList = backReturnOrderService.findProductIdList(did, clientId);
        List<Product> product1 = new ArrayList<>();
        for(ProductId products : findProductIdList){
            Product product = new Product();
            String mid = products.getMid();
            String productId = products.getId();
            Product findProduct = backReturnOrderService.findProduct(mid, productId);
            if(findProduct.getTargetType().equals("M")){
                String findAbbreviation = backReturnOrderService.findAbbreviation(mid);
                product.setTargetId(mid);
                product.setAbbreviation(findAbbreviation);
                product.setId(productId);
                product.setName(findProduct.getName());
                product.setBarcode(findProduct.getBarcode());
                product1.add(product);
            }
            if(findProduct.getTargetType().equals("D")){
                product.setTargetId(mid);
                product.setAbbreviation("自营");
                product.setId(productId);
                product.setName(findProduct.getName());
                product.setBarcode(findProduct.getBarcode());
                product1.add(product);
            }
        }

        return new DstoreInExcution<List<Product>>(product1, DstoreInEnum.SUCCESS);
    }

}
